package cn.mason.echarts.controller;

import cn.mason.echarts.config.Constant;
import cn.mason.echarts.model.UserFile;
import cn.mason.echarts.service.FileService;
import com.baomidou.kisso.SSOHelper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
public class FileController {
    @Autowired
    RestTemplate restTemplate;
    FileService fileService;
    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/file")
    public String fileUploadPage() {
        return "file/upload";
    }

    @HystrixCommand(fallbackMethod = "fileUploadError")
    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> fileUpload(@RequestParam("file")MultipartFile file,HttpServletRequest request) throws IOException{
        File temp=new File(file.getOriginalFilename());
        temp.createNewFile();
        FileOutputStream fileOutputStream=new FileOutputStream(temp);
        fileOutputStream.write(file.getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
        FileSystemResource fileSystemResource=new FileSystemResource(temp);


        MultiValueMap param=new LinkedMultiValueMap();
        param.add("file",fileSystemResource);
        param.add("filepath","/"+SSOHelper.getSSOToken(request).getId());
        ResponseEntity<String> responseEntity=restTemplate.postForEntity("http://SERVICE-FILE/uploadFile",param,String.class);
        temp.delete();
        return ResponseEntity.status(HttpStatus.OK).body(responseEntity.getBody());
    }


    @RequestMapping(value = "/data",method = RequestMethod.GET)
    public String file(HttpServletRequest request, Model model) {
        File targetFilePath=new File(Constant.FILE_PATH+SSOHelper.getSSOToken(request).getId());
        File[] files=targetFilePath.listFiles();
        List<UserFile> list= new ArrayList();
        if(files!=null&&files.length!=0){
            for(int i=0;i<files.length;i++){
                UserFile userFile=new UserFile();
                userFile.setName(files[i].getName());
                userFile.setOwner("mason");
                userFile.setCreateTime("2018.6.10");
                list.add(userFile);
            }
        }

        model.addAttribute("list",list);
        return "data";
    }

    @RequestMapping(value = "/listFile",method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<List> listFile(HttpServletRequest request, Model model) {
        File targetFilePath=new File(Constant.FILE_PATH+SSOHelper.getSSOToken(request).getId());
        File[] files=targetFilePath.listFiles();
        List<String> list= new ArrayList();
        for(int i=0;i<files.length;i++){
            list.add(files[i].getName());
        }
        return  ResponseEntity.status(HttpStatus.OK).body(list);
    }

    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        String filename=file.getOriginalFilename();
        try {
            File targetFilePath=new File(Constant.FILE_PATH+SSOHelper.getSSOToken(request).getId());
            if(!targetFilePath.exists()){
                targetFilePath.mkdirs();
            }
            File file1=new File(targetFilePath+"/"+filename);
            file1.createNewFile();
            FileOutputStream fileOutputStream=new FileOutputStream(file1);
            fileOutputStream.write(file.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            return "success";
        } catch (IOException ioe){
            return "error";
        }
    }

    @RequestMapping(value = "/rmFile/{file}",method = RequestMethod.GET)
    public String rmFile(@PathVariable("file") String file, HttpServletRequest request) {
        String filename=SSOHelper.getSSOToken(request).getId()+"/"+file;
        File file1=new File(Constant.FILE_PATH+filename);
        if(file1.exists()){
            file1.delete();
        }
        return "redirect:/data";
    }



    @RequestMapping(value = "/downFile/{file}",method = RequestMethod.GET)
    public void downFile(@PathVariable("file") String file, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String filename=SSOHelper.getSSOToken(request).getId()+"/"+file;
        File file1=new File(Constant.FILE_PATH+filename);
        if(file1.exists()){
            request.setCharacterEncoding("UTF-8");
            String name = Constant.FILE_PATH+filename;//获取要下载的文件名
            response.setContentType("application/force-download");//应用程序强制下载
            InputStream in = new FileInputStream(file1);

            response.setHeader("Content-Disposition", "attachment;filename="+file);
            response.setContentLength(in.available());

            OutputStream out = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len = in.read(b))!=-1){
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        }
    }
}
